package com.example.sprintboot.service;

import com.example.sprintboot.entity.Cart;
import com.example.sprintboot.entity.Order;
import com.example.sprintboot.entity.OrderItem;
import com.example.sprintboot.mapper.CartMapper;
import com.example.sprintboot.mapper.OrderMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private CartMapper cartMapper;

    @Transactional
    public Order createOrder(Integer userId, List<Cart> cartItems) {
        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setCreateTime(new Date());
        
        // 计算总价并创建订单项
        double totalPrice = 0.0;
        List<OrderItem> orderItems = new ArrayList<>();
        
        for (Cart cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setBookId(cartItem.getBookId());
            orderItem.setBookName(cartItem.getName());
            orderItem.setPrice(cartItem.getPrice().doubleValue());
            orderItem.setQuantity(cartItem.getNum());
            orderItem.setAuthor(cartItem.getAuthor());
            orderItem.setIsbn(cartItem.getIsbn());
            
            totalPrice += orderItem.getPrice() * orderItem.getQuantity();
            orderItems.add(orderItem);
        }
        
        order.setTotalPrice(totalPrice);
        
        // 保存订单
        orderMapper.insertOrder(order);
        
        // 设置订单项的orderId并保存
        for (OrderItem item : orderItems) {
            item.setOrderId(order.getId());
        }
        orderMapper.insertOrderItems(orderItems);
        
        // 清空用户购物车
        for (Cart cartItem : cartItems) {
            cartMapper.deleteById(cartItem.getId());
        }
        
        order.setOrderItems(orderItems);
        return order;
    }

    public List<Order> getUserOrders(Integer userId) {
        return orderMapper.selectByUserId(userId);
    }

    public Order getOrderById(Integer orderId) {
        return orderMapper.selectById(orderId);
    }
} 